package downloadtask;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.EventObject;

class DownloadThreadEvent extends EventObject {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    Object sourObject;
    long count;

    // public DownloadThreadEvent()
    // {
    //
    // }
    public DownloadThreadEvent(Object sourceObject, long count) {
        super(sourceObject);
        this.sourObject = sourceObject;
        this.count = count;
    }

    long getCount() {
        return count;
    }

    Object getTarget() {
        return sourObject;
    }
}

class DownloadThread extends Thread {

    String url;
    long startPosition;
    long endPosition;
    boolean isRange;
    File file;
    DownloadThreadListener listener;
    long downloaded;

    void addDownloadListener(DownloadThreadListener listener) {
        this.listener = listener;
    }

    public long getdownLoaded() {
        return this.downloaded;
    }

    DownloadThread(String url, long startPosition, long endPosition, File file) {
        this.url = url;
        this.startPosition = startPosition;
        this.endPosition = endPosition;
        this.isRange = true;
        this.file = file;
        this.downloaded = 0;
    }

    DownloadThread(String url, long startPosition, long endPosition, File file,
                   boolean isRange) {
        this.url = url;
        this.startPosition = startPosition;
        this.endPosition = endPosition;
        this.isRange = isRange;
        this.file = file;
        this.downloaded = 0;
    }

    public void run() {

        //Log.info("Start:" + startPosition + "-" + endPosition);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        CloseableHttpClient httpClient = httpClientBuilder.build();
        try {
            HttpGet httpGet = new HttpGet(url);
            if (isRange) {// 多线程下载
                httpGet.addHeader("Range", "bytes=" + startPosition + "-"
                        + endPosition);
            }
            HttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 206 || (statusCode == 200 && !isRange)) {
                java.io.InputStream inputStream = response.getEntity()
                        .getContent();
                RandomAccessFile outputStream = new RandomAccessFile(file, "rw");
                outputStream.seek(startPosition);
                int count = 0;
                byte[] buffer = new byte[10240];
                while ((count = inputStream.read(buffer, 0, buffer.length)) > 0) {
                    outputStream.write(buffer, 0, count);
                    downloaded += count;
                    listener.afterPerDown(new DownloadThreadEvent(this, count));
                }
                outputStream.close();
            }
            httpGet.abort();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            listener.downCompleted(new DownloadThreadEvent(this, endPosition));
            if (DownloadTask.getDebug()) {
                System.out.println("End:" + startPosition + "-" + endPosition);
            }
            try {
                httpClient.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }

}

